<template>
  <!-- Cesium视图容器 -->
  <div id="cesiumContainer" ref="cesiumContainer">
    <!-- 设备管理组件 -->
    <DeviceManager 
      :viewer="viewer" 
      ref="deviceManager" 
      v-if="viewer"
    />
    
    <!-- 地块管理组件 -->
    <ParcelManager 
      :viewer="viewer" 
      ref="parcelManager" 
      v-if="viewer"
    />
    
    <!-- 快速操作面板 -->
    <QuickActions 
      :viewer="viewer" 
      ref="quickActions" 
      v-if="viewer"
      @toggle-devices="handleToggleDevices"
      @toggle-parcels="handleToggleParcels"
      @refresh-data="handleRefreshData"
    />
    
    <!-- 系统信息面板 -->
    <div class="system-info">
      <div class="info-item">
        <span class="label">农机监控系统</span>
        <span class="version">v1.0</span>
      </div>
      <div class="connection-status" :class="{ connected: isConnected }">
        <span class="status-dot"></span>
        <span>{{ isConnected ? '已连接' : '连接中...' }}</span>
      </div>
    </div>
    
    <!-- 工具栏 -->
    <div class="toolbar">
      <button @click="resetView" class="tool-btn" title="重置视角">
        🏠
      </button>
      <button @click="toggleFullscreen" class="tool-btn" title="全屏">
        ⛶
      </button>
      <button @click="toggleHelp" class="tool-btn" title="帮助">
        ❓
      </button>
    </div>
    
    <!-- 帮助面板 -->
    <div class="help-panel" v-if="showHelp">
      <div class="help-header">
        <h3>使用说明</h3>
        <button @click="toggleHelp" class="close-btn">×</button>
      </div>
      <div class="help-content">
        <h4>功能介绍：</h4>
        <ul>
          <li><strong>设备管理：</strong>查看农机实时位置、状态，播放历史轨迹</li>
          <li><strong>地块管理：</strong>显示地块边界，分析作业面积</li>
          <li><strong>轨迹播放：</strong>支持按时间段查询和播放农机轨迹</li>
          <li><strong>空间分析：</strong>计算农机在地块内的有效作业面积</li>
        </ul>
        <h4>操作指南：</h4>
        <ul>
          <li>鼠标左键拖拽：旋转视角</li>
          <li>鼠标右键拖拽：平移视角</li>
          <li>鼠标滚轮：缩放视角</li>
          <li>点击设备或地块：查看详细信息</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as Cesium from 'cesium'; // 从node_modules中导入Cesium
import "./Widgets/widgets.css";   // 从src下导入Cesium的样式
import { onMounted, ref } from 'vue'; // 导入声明周期"挂载"和ref
import DeviceManager from './components/DeviceManager.vue';
import ParcelManager from './components/ParcelManager.vue';
import QuickActions from './components/QuickActions.vue';

// 设置Cesium的静态资源路径
window.CESIUM_BASE_URL = "/";

// 创建一个对DOM元素的引用
const cesiumContainer = ref(null);
const deviceManager = ref(null);
const parcelManager = ref(null);
const quickActions = ref(null);
const viewer = ref(null);
const isConnected = ref(false);
const showHelp = ref(false);

// 组件挂载后执行的代码
onMounted(() => {
  // 初始化viewer，并将其绑定到ref="cesiumContainer"的div中
  viewer.value = new Cesium.Viewer(cesiumContainer.value, {
     infoBox: false,//禁止信息窗口显示
    geocoder: false,//禁止搜索框显示
    homeButton: false,//禁止home按钮显示
    sceneModePicker: false,//禁止切换3D/2D按钮显示
    baseLayerPicker: false,//禁止图层选择器显示
    navigationHelpButton: false,//禁止帮助按钮显示
    animation: true, // 启用动画小部件（轨迹播放需要）
    timeline: true,  // 启用时间轴（轨迹播放需要）
    fullscreenButton: false, // 禁用全屏按钮
    vrButton: false, // 禁用VR按钮
  });

  //隐藏logo
  viewer.value.cesiumWidget.creditContainer.style.display = "none";
  
  // 设置初始视角到中国
  viewer.value.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 50000), // 北京
    orientation: {
      heading: 0.0,
      pitch: -Cesium.Math.PI_OVER_TWO * 0.5,
      roll: 0.0
    }
  });
  
  // 模拟连接状态
  setTimeout(() => {
    isConnected.value = true;
    // 初始化数据显示
    initializeDataDisplay();
  }, 2000);
  
  // 使用Cesium的官方点击事件处理
  viewer.value.screenSpaceEventHandler.setInputAction((click) => {
    onMapClick({ position: click.position });
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  
  // 添加右键菜单禁用
  viewer.value.cesiumWidget.canvas.addEventListener('contextmenu', (e) => {
    e.preventDefault();
  });
});

// 地图点击事件
const onMapClick = (event) => {
  // 检查事件和位置是否存在
  if (!event || !event.position) {
    return;
  }
  
  try {
    const pickedObject = viewer.value.scene.pick(event.position);
    if (Cesium.defined(pickedObject)) {
      const entity = pickedObject.id;
      if (entity) {
        // 显示实体信息
        showEntityInfo(entity);
      }
    }
  } catch (error) {
    console.warn('点击事件处理失败:', error);
  }
};

// 显示实体信息
const showEntityInfo = (entity) => {
  const infoDiv = document.createElement('div');
  infoDiv.className = 'entity-info-popup';
  infoDiv.innerHTML = `
    <h4>${entity.name || '未知'}</h4>
    <p>ID: ${entity.id}</p>
    <button onclick="this.parentElement.remove()">关闭</button>
  `;
  
  infoDiv.style.cssText = `
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 10px;
    border-radius: 5px;
    z-index: 10000;
    min-width: 200px;
  `;
  
  document.body.appendChild(infoDiv);
  
  // 3秒后自动关闭
  setTimeout(() => {
    if (infoDiv.parentElement) {
      infoDiv.parentElement.removeChild(infoDiv);
    }
  }, 3000);
};

// 重置视角
const resetView = () => {
  viewer.value.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 50000),
    orientation: {
      heading: 0.0,
      pitch: -Cesium.Math.PI_OVER_TWO * 0.5,
      roll: 0.0
    }
  });
};

// 切换全屏
const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen();
  } else {
    document.documentElement.requestFullscreen();
  }
};

// 切换帮助面板
const toggleHelp = () => {
  showHelp.value = !showHelp.value;
};

// 快速操作事件处理
const handleToggleDevices = (show) => {
  if (deviceManager.value) {
    if (show) {
      deviceManager.value.updateDeviceEntities();
    } else {
      // 隐藏设备实体
      const deviceEntities = viewer.value.entities.values.filter(entity => 
        entity.id && entity.id.toString().startsWith('device_')
      );
      deviceEntities.forEach(entity => {
        entity.show = false;
      });
    }
  }
};

const handleToggleParcels = (show) => {
  if (parcelManager.value) {
    if (show) {
      parcelManager.value.updateParcelEntities();
    } else {
      parcelManager.value.clearParcelEntities();
    }
  }
};

const handleRefreshData = () => {
  // 刷新所有数据
  if (deviceManager.value) {
    deviceManager.value.refreshDevices();
  }
  if (parcelManager.value) {
    parcelManager.value.refreshParcels();
  }
  if (quickActions.value) {
    setTimeout(() => {
      quickActions.value.updateStats();
    }, 1000);
  }
};

// 初始化数据显示
const initializeDataDisplay = () => {
  // 稍后初始化，等待组件加载完成
  setTimeout(() => {
    handleRefreshData();
    
    // 自动定位到数据区域
    setTimeout(() => {
      const allEntities = viewer.value.entities.values;
      if (allEntities.length > 0) {
        viewer.value.flyTo(allEntities, {
          duration: 3.0
        }).catch(error => {
          console.warn('自动定位失败:', error);
        });
      }
    }, 2000);
  }, 500);
};

//设置cesium的默认视角(从默认美国改为中国)
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
  89.5,//西边经度
  20.4,//南边纬度
  110.4,//南边经度
  61.2//北边纬度
);
</script>

<style>
* {
  margin: 0;
  padding: 0;
}

#cesiumContainer {
  width: 100vw;
  /* 使用视口宽度 */
  height: 100vh;
  /* 使用视口高度 */
}

/* 系统信息面板 */
.system-info {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 15px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  z-index: 1000;
  font-size: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.info-item .label {
  font-weight: bold;
}

.info-item .version {
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #dc3545;
  animation: pulse 2s infinite;
}

.connection-status.connected .status-dot {
  background: #28a745;
  animation: none;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

/* 工具栏 */
.toolbar {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
  z-index: 1000;
}

.tool-btn {
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  transition: all 0.2s ease;
}

.tool-btn:hover {
  background: rgba(0, 0, 0, 0.9);
  transform: scale(1.1);
}

/* 帮助面板 */
.help-panel {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  max-height: 60vh;
  background: rgba(0, 0, 0, 0.9);
  color: white;
  border-radius: 10px;
  z-index: 10000;
  overflow: hidden;
}

.help-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: rgba(255, 255, 255, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.help-header h3 {
  margin: 0;
  font-size: 18px;
}

.help-header .close-btn {
  background: transparent;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.help-header .close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.help-content {
  padding: 20px;
  max-height: calc(60vh - 80px);
  overflow-y: auto;
}

.help-content h4 {
  margin: 0 0 10px 0;
  color: #ffc107;
  font-size: 14px;
}

.help-content ul {
  margin: 0 0 20px 0;
  padding-left: 20px;
}

.help-content li {
  margin-bottom: 8px;
  font-size: 13px;
  line-height: 1.4;
}

.help-content strong {
  color: #17a2b8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .system-info {
    left: 10px;
    right: 10px;
    transform: none;
    font-size: 11px;
  }
  
  .help-panel {
    width: 90vw;
    max-width: none;
  }
  
  .toolbar {
    right: 5px;
  }
  
  .tool-btn {
    width: 35px;
    height: 35px;
    font-size: 14px;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* Cesium 动画和时间轴容器样式调整 */
.cesium-viewer-animationContainer {
  width: 180px !important;
}

.cesium-viewer-timelineContainer {
  left: 190px !important;
  right: 10px !important;
}

.cesium-animation-svg {
  width: 160px !important;
  height: 75px !important;
}
</style>
